package com.liming.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liming.common.pojo.entity.order.OrderItem;
import com.liming.common.pojo.vo.order.mini.MiniOrderItemVO;
import com.liming.common.pojo.vo.product.openfeign.FeignProductVO;
import com.liming.common.util.mybatisplus.MPUtil;
import com.liming.order.mapper.OrderItemMapper;
import com.liming.order.service.OrderItemMircoService;
import com.liming.product.client.ProductClient;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liming
 * @date 2025/2/5
 */
@Service
@AllArgsConstructor
public class OrderItemMircoServiceImpl extends ServiceImpl<OrderItemMapper, OrderItem>
        implements OrderItemMircoService, MPUtil<OrderItem> {

    private final ProductClient productClient;

    @Override
    public List<OrderItem> listByOrderId(Long id) {
        return lambdaQuery().eq(OrderItem::getOrderId, id).list();
    }

    @Override
    public List<Long> productIdListByOrderIdList(List<Long> keyIdList) {
        return lambdaQuery().in(OrderItem::getOrderId, keyIdList).list().stream().map(OrderItem::getProductId).distinct().collect(Collectors.toList());
    }

    @Override
    public List<MiniOrderItemVO> itemsByOrderId(Long id) {
        List<MiniOrderItemVO> miniOrderItems = lambdaQuery().eq(OrderItem::getOrderId, id).list().stream().map(entity -> {
            MiniOrderItemVO vo = new MiniOrderItemVO();
            BeanUtils.copyProperties(entity, vo);
            return vo;
        }).toList();
        Map<Long, String> productIdAndImage = productClient.listByIds(miniOrderItems.stream().map(MiniOrderItemVO::getProductId).toList()).stream().collect(Collectors.toMap(FeignProductVO::getId, FeignProductVO::getMainImageUrl));
        for (MiniOrderItemVO miniOrderItem : miniOrderItems) {
            String image = productIdAndImage.getOrDefault(miniOrderItem.getProductId(), "");
            miniOrderItem.setProductImage(image);
        }
        return miniOrderItems;
    }
}
